package com.mage.myshop.directive;

import com.mage.myshop.model.Category;
import com.mage.myshop.service.CategoryService;
import freemarker.core.Environment;
import freemarker.ext.beans.BeansWrapper;
import freemarker.ext.beans.BeansWrapperBuilder;
import freemarker.ext.beans.NumberModel;
import freemarker.template.*;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.Writer;
import java.util.List;
import java.util.Map;

@Component
public class ChildrenCategoryDirective implements TemplateDirectiveModel {

    @Resource
    private CategoryService categoryService;

    @Override
    public void execute(Environment env, Map params,
                        TemplateModel[] loopVars,
                        TemplateDirectiveBody body)
            throws TemplateException, IOException {

        // 获取父类ID
        NumberModel parentId = ((NumberModel) params.get("parentId"));
        if (parentId == null) {
            throw new TemplateModelException("请输入父类ID");
        }

        SimpleNumber limit = (SimpleNumber) params.get("limit");

        // 查询数据
        List<Category> categories = categoryService.findChildren(parentId.getAsNumber().intValue(), limit);

        // 输出数据
        if (body == null) {
            throw new TemplateModelException("模板输出错误。");
        }
        Writer out = env.getOut();
        // 设置结果
        BeansWrapper beansWrapper = new BeansWrapperBuilder(Configuration.VERSION_2_3_29).build();
        env.setVariable("children", beansWrapper.wrap(categories));
        body.render(out);
    }
}
